package com.sugon.api;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.cait.service.ResCenterClient;
import com.cait.service.rescenter.ResultMessage;
import com.cait.service.rescenter.UserInfo;
import com.sugon.annotation.AuthCheck;
import com.sugon.annotation.IgnoreAuth;
import com.sugon.annotation.LoginUser;
import com.sugon.consts.CommonConstant;
import com.sugon.dao.SysDeptDao;
import com.sugon.dao.SysRoleDao;
import com.sugon.dao.SysUserDao;
import com.sugon.dao.SysUserRoleDao;
import com.sugon.entity.ApiResult;
import com.sugon.entity.SysDeptEntity;
import com.sugon.entity.SysRoleEntity;
import com.sugon.entity.SysUserEntity;
import com.sugon.entity.dto.AppIndexMenuGridDTO;
import com.sugon.entity.dto.AppIndexMenuGridItemDTO;
import com.sugon.entity.dto.UViewSelectOptionDTO;
import com.sugon.modules.sys.consts.SysRole;
import com.sugon.modules.sys.model.vo.PickerModel;
import com.sugon.modules.sys.service.IResCenterAuthenticator;
import com.sugon.service.*;
import com.sugon.util.RsaUtil;
import com.sugon.utils.Constant;
import com.sugon.utils.RRException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.rmi.RemoteException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户登录
 */
@Slf4j
@Api(tags = "用户接口")
@RestController
@RequestMapping("/api/v1")
public class UserApiController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private SysDeptService sysDeptService;
    @Autowired
    private SysConfigService configService;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private SysUserRoleDao sysUserRoleDao;
    @Resource
    private SysRoleDao roleDao;
    @Autowired
    private SysDeptDao sysDeptDao;
    @Autowired
    private SysUserService userService;
    @Resource
    private DevMaintenanceTicketService devMaintenanceTicketService;
    @Resource
    private DevAmTicketService devAmTicketService;
    @Autowired
    private IResCenterAuthenticator resCenterAuthenticator;
    @Resource
    private BaseCommonService baseCommonService;

    @IgnoreAuth
    @ApiOperation(value = "获取铸造车间列表API")
    @PostMapping("/loadCastWorkshop")
    public ApiResult<List<SysDeptEntity>> loadWorkshop() {
        ApiResult<List<SysDeptEntity>> apiResult = new ApiResult<>();
        return apiResult.success(sysDeptService.getZhuZCJ());
    }

    @ApiOperation(value = "获取车间室主任列表API")
    @PostMapping("/spareApproverList")
    public ApiResult<List<SysUserEntity>> spareApproverList(@ApiIgnore @LoginUser SysUserEntity sysUser) {
        ApiResult<List<SysUserEntity>> apiResult = new ApiResult<>();
        return apiResult.success(userService.listSpareApprover(sysUser.getDeptCode()));
    }

    @ApiOperation(value = "获取领导列表API")
    @ApiImplicitParam(name = "keyword", value = "用户名或用户姓名", required = true, dataType = "string", paramType = "query")
    @PostMapping("/loadLeaderList")
    public ApiResult<List<PickerModel>> loadLeaderList(@RequestParam String keyword) {
        ApiResult<List<PickerModel>> apiResult = new ApiResult<>();
        List<PickerModel> leaderList = CollectionUtil.newArrayList();
        // 查询匹配用户
        Map<String, Object> param = MapUtil.newHashMap();
        param.put("keyword", keyword);
        param.put("leader", 1);
        List<SysUserEntity> userList = userService.queryList(param);
        if (CollectionUtil.isNotEmpty(userList)) {
            leaderList.addAll(userList.stream().map(user -> new PickerModel(StrUtil.format("{}({})", user.getNickName(), user.getUserName()), user.getUserId())).collect(Collectors.toList()));
        }
        return apiResult.success(leaderList);
    }

    @AuthCheck
    @ApiOperation(value = "获取当前登录用户所在车间的指定角色的用户列表API")
    @ApiImplicitParam(name = "roleCode", value = "角色代码", required = true, dataType = "string", paramType = "query")
    @PostMapping("/loadWorkshopRoleUserList")
    public ApiResult<List<PickerModel>> loadWorkshopRoleUserList(@ApiIgnore @LoginUser SysUserEntity sysUser, @RequestParam String roleCode) {
        ApiResult<List<PickerModel>> apiResult = new ApiResult<>();
        List<PickerModel> leaderList = CollectionUtil.newArrayList();
        List<PickerModel> leaderList2 = CollectionUtil.newArrayList();
        // 校验角色是否存在
        List<SysRoleEntity> roleList = roleDao.listByRoleCode(roleCode);
        if (CollectionUtil.isEmpty(roleList)) {
            return apiResult.failMsg("角色不存在，请确认！");
        }
        List<SysUserEntity> userList = sysUserRoleDao.queryWorkshopRoleUser(sysUser.getWorkShopId(), roleList.get(0).getRoleId());
        if (CollectionUtil.isNotEmpty(userList)) {
            leaderList.addAll(userList.stream().map(user -> new PickerModel(StrUtil.format("{}({})", user.getNickName(), user.getUserName()), user.getUserId())).collect(Collectors.toList()));
        }
        // 简单处理，将自己放到首位，方便选择
        for (PickerModel pickerModel : leaderList) {
            if (sysUser.getUserId().equals(pickerModel.getValue())) {
                leaderList2.add(0, pickerModel);
            } else {
                leaderList2.add(pickerModel);
            }
        }
        return apiResult.success(leaderList2);
    }

    @IgnoreAuth
    @ApiOperation(value = "获取产线列表API")
    @PostMapping("/loadLineList")
    public ApiResult<List<UViewSelectOptionDTO>> loadLineList() {
        ApiResult<List<UViewSelectOptionDTO>> apiResult = new ApiResult<>();
        List<SysDeptEntity> list = new ArrayList<>();
        // 获取工厂和车间
        List<SysDeptEntity> tyList = sysDeptDao.queryListByTY();
        // 获取产线
        List<SysDeptEntity> lineList = sysDeptDao.queryListLTLevel(3);
        list.addAll(tyList);
        list.addAll(lineList);
        return apiResult.success(handleFromSysDeptList(list));
    }

    @AuthCheck
    @ApiOperation(value = "获取APP首页菜单API")
    @PostMapping("/loadIndexMenu")
    public ApiResult<List<AppIndexMenuGridDTO>> loadIndexMenu(@ApiIgnore @LoginUser SysUserEntity sysUser) {
        ApiResult<List<AppIndexMenuGridDTO>> apiResult = new ApiResult<>();
        // 获取所有菜单grid项
        List<AppIndexMenuGridDTO> menuGridList = initIndexMenu();

        /*
            过滤菜单项
            生产班组长
            维修组长
            维修工
            车间工艺工程师
         */
        // 获取用户的角色信息
        List<String> roleIdList = sysUserRoleDao.queryRoleIdList(sysUser.getUserId());
        // 获取登录用户的部门类别
        String deptId = sysUser.getDeptId();
        if (StrUtil.isNotEmpty(deptId)) {
            String type = sysDeptService.getDeptTypeById(deptId);
            // 根据用户所在的部门ID和角色，过滤，只保留用户可以看到的
            menuGridList = filterIndexMenu(menuGridList, type, roleIdList);
            // 设置设备工单的角标
            for (AppIndexMenuGridDTO indexMenuGrid : menuGridList) {
                if (StrUtil.containsAny(indexMenuGrid.getTitle(), "设备")) {
                    List<AppIndexMenuGridItemDTO> gridItems = indexMenuGrid.getGridItems();
                    for (AppIndexMenuGridItemDTO gridItem : gridItems) {
                        if ("设备维护".equals(gridItem.getGridText())) {
                            // 获取当前用户未完成的设备维护工单数并设置
                            int unCompleteTicketNum = devMaintenanceTicketService.countUnCompleteTicketNum(sysUser);
                            gridItem.setBadgeCount(unCompleteTicketNum);
                        } else if ("自主维护".equals(gridItem.getGridText())) {
                            // 获取当前用户未完成的设备自主维护工单数并设置
                            int unCompleteAmTicketNum = devAmTicketService.countUnCompleteTicketNum(sysUser);
                            gridItem.setBadgeCount(unCompleteAmTicketNum);
                        }
                    }
                }
            }
        }
        return apiResult.success(menuGridList);
    }

    /**
     * 根据用户所在的部门和角色ID过滤首页菜单
     * 如果每个菜单中不包含任何项，页会移除
     *
     * @param indexMenuList 首页菜单列表
     * @param deptType      部门类型， 取值自SYS_DEPT 表的DEPT_TYPE 字段值
     * @param roleIdList    角色ID列表
     * @return
     */
    private List<AppIndexMenuGridDTO> filterIndexMenu(List<AppIndexMenuGridDTO> indexMenuList, String deptType, List<String> roleIdList) {
        List<AppIndexMenuGridDTO> filteredIndexMenuList = CollectionUtil.newArrayList();
        for (AppIndexMenuGridDTO indexMenu : indexMenuList) {
            List<AppIndexMenuGridItemDTO> gridItems = indexMenu.getGridItems();
            gridItems = gridItems.stream().filter(gridItem -> CollectionUtil.contains(gridItem.getDeptCodeList(), deptType) || CollectionUtil.containsAny(roleIdList, gridItem.getRoleIdList())).collect(Collectors.toList());
            if (CollectionUtil.isEmpty(gridItems)) {
                continue;
            }
            indexMenu.setGridItems(gridItems);
            filteredIndexMenuList.add(indexMenu);
        }
        return filteredIndexMenuList;
    }

    /**
     * 初始化首页菜单，会返回首页的所有菜单项
     * 等待进一步初始化
     *
     * @return
     */
    private List<AppIndexMenuGridDTO> initIndexMenu() {
        List<AppIndexMenuGridDTO> menuGridList = new ArrayList<>();
        // 设备模块
        AppIndexMenuGridDTO deviceModule = new AppIndexMenuGridDTO("设备模块");
        deviceModule.addItem(new AppIndexMenuGridItemDTO("设备清单", "iconfont icon-gongdanliebiao", 0, "../device/base/newList", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList(SysRole.SCQZ.getRoleId(), SysRole.DNG.getRoleId())));
        deviceModule.addItem(new AppIndexMenuGridItemDTO("一键报修", "iconfontIconScan icon-saoma-big", 0, "../device/base/callRepair", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList(SysRole.SCQZ.getRoleId(), SysRole.DNG.getRoleId())));
        deviceModule.addItem(new AppIndexMenuGridItemDTO("设备维护", "iconfont icon-weihu1", 0, "../device/maintenance/list", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList()));
        deviceModule.addItem(new AppIndexMenuGridItemDTO("设备维修", "iconfont icon-weixiu", 0, "../device/repair/list", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList()));
        deviceModule.addItem(new AppIndexMenuGridItemDTO("设备巡检", "iconfont icon-gongdixunjian", 0, "../device/inspect/list", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList()));
        deviceModule.addItem(new AppIndexMenuGridItemDTO("自主维护", "iconfontIconScan icon-weihu", 0, "../device/am/list", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList(SysRole.SCQZ.getRoleId(), SysRole.DNG.getRoleId())));
        // 备件模块
        AppIndexMenuGridDTO sparePartsModule = new AppIndexMenuGridDTO("备件模块");
        sparePartsModule.addItem(new AppIndexMenuGridItemDTO("备件清单", "iconfont icon-gongdanliebiao", 0, "../sparepart/sparepartList", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList(SysRole.BJGLZY.getRoleId())));
        sparePartsModule.addItem(new AppIndexMenuGridItemDTO("库存查询", "iconfont icon-kucunchaxun2", 0, "../sparepart/sparepartStock", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList(SysRole.BJGLZY.getRoleId())));
        sparePartsModule.addItem(new AppIndexMenuGridItemDTO("发起领料", "iconfont icon-lingliaodan", 0, "../sparepart/materialRequisition", CollectionUtil.newArrayList("DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC"), CollectionUtil.newArrayList(SysRole.BJGLZY.getRoleId())));
        //sparePartsModule.addItem(new AppIndexMenuGridItemDTO("临时接入", "iconfont icon-weixiufuwu", 0, "../repair/repairSingleList"));
        // 模具模块
        AppIndexMenuGridDTO moldModule = new AppIndexMenuGridDTO("模具模块");
        // 模具用户角色列表，一般都一样，如果不一样则自己添加
        List<String> moldUserRoleList = CollectionUtil.newArrayList(SysRole.MXZZ.getRoleId(), SysRole.SCZZ_MJWX.getRoleId(), SysRole.ZZCJSZLSZR_MJ.getRoleId(), SysRole.CJJSZLSZR_MJ.getRoleId(), SysRole.CJZZGYGCS.getRoleId(), SysRole.ZZCZZGYGCS.getRoleId());
        moldModule.addItem(new AppIndexMenuGridItemDTO("模具档案", "iconfont icon-gongdanliebiao", 0, "../moldModule/moduleList", CollectionUtil.newArrayList("DT_MJWXZ", "DT_MJJSS"), moldUserRoleList));
        moldModule.addItem(new AppIndexMenuGridItemDTO("模具型芯", "iconfont icon-gongdanliebiao", 0, "../moldModule/moldSpList", CollectionUtil.newArrayList("DT_MJWXZ", "DT_MJJSS"), moldUserRoleList));
        moldModule.addItem(new AppIndexMenuGridItemDTO("定期维护", "iconfont icon-weihu1", 0, "../mold/maintenance/list", CollectionUtil.newArrayList("DT_MJWXZ", "DT_MJJSS"), moldUserRoleList));
        moldModule.addItem(new AppIndexMenuGridItemDTO("紧急维护", "iconfont icon-weixiu1", 0, "../mold/repair/list", CollectionUtil.newArrayList("DT_MJWXZ", "DT_MJJSS"), moldUserRoleList));
        moldModule.addItem(new AppIndexMenuGridItemDTO("型芯出库", "iconfontIconScan icon-saoma-big", 0, "../mold/sancodeOutbound/list", CollectionUtil.newArrayList("DT_MJWXZ", "DT_MJJSS"), moldUserRoleList));
        // 工装模块
        AppIndexMenuGridDTO toolsModule = new AppIndexMenuGridDTO("工装模块");
        toolsModule.addItem(new AppIndexMenuGridItemDTO("检测工单", "iconfont icon-gongdanliebiao", 0, "../workClothes/equipment", CollectionUtil.newArrayList("DT_JSZLS"), CollectionUtil.newArrayList()));
        // 构建返回菜单
        menuGridList.add(deviceModule);
        menuGridList.add(sparePartsModule);
        menuGridList.add(moldModule);
        menuGridList.add(toolsModule);
        return menuGridList;
    }

    @AuthCheck
    @ApiOperation(value = "绑定移动端CLIENT_ID接口API")
    @ApiImplicitParam(name = "clientId", value = "CLIENT_ID", paramType = "query", dataType = "String", required = true)
    @PostMapping("/bingAppClient")
    public ApiResult<String> bindAppClient(@ApiIgnore @LoginUser SysUserEntity loginUser, @RequestParam String clientId) {
        ApiResult<String> apiResult = new ApiResult<>();
        return sysUserDao.updateClientId(loginUser.getUserId(), clientId) > 0 ? apiResult.success() : apiResult.fail();
    }

    /**
     * List<UViewSelectOptionDTO>
     *
     * @param list
     * @return
     */
    private List<UViewSelectOptionDTO> handleFromSysDeptList(List<SysDeptEntity> list) {
        // 1、将List<SysDeptEntity> -> List<UViewSelectOptionDTO>
        List<UViewSelectOptionDTO> optionList = new ArrayList<>();
        for (SysDeptEntity sysDeptEntity : list) {
            optionList.add(new UViewSelectOptionDTO(sysDeptEntity));
        }
        // 构建父子结构部门树
        List<UViewSelectOptionDTO> deptTreeList = optionList.stream().filter(m -> "01".equals(m.getParentId())).map(
                (m) -> {
                    m.setChildren(getChildrens(m, optionList));
                    return m;
                }
        ).collect(Collectors.toList());
        // 过滤掉没有子部门的
        return deptTreeList.stream().filter(deptNode -> CollectionUtil.isNotEmpty(deptNode.getChildren())).collect(Collectors.toList());
    }

    /**
     * 递归查询子节点
     *
     * @param root 根节点
     * @param all  所有节点
     * @return 根节点信息
     */
    private List<UViewSelectOptionDTO> getChildrens(UViewSelectOptionDTO root, List<UViewSelectOptionDTO> all) {
        List<UViewSelectOptionDTO> children = all.stream().filter(m -> {
            return Objects.equals(m.getParentId(), root.getValue());
        }).map(
                (m) -> {
                    m.setChildren(getChildrens(m, all));
                    return m;
                }
        ).collect(Collectors.toList());
        return children;
    }

    @IgnoreAuth
    @ApiOperation(value = "用户登录(flag 0:模修工  1:机电维修工)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "username", value = "用户名", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "password", value = "密码", paramType = "query", dataType = "String", required = true),
            @ApiImplicitParam(name = "isEncrypted", value = "是否加密", paramType = "query", dataType = "String")
    })
    @PostMapping("/login")
    public ApiResult<Map> login(@RequestParam("username") String username, @RequestParam("password") String password, String isEncrypted) {
        ApiResult<Map> apiResult = new ApiResult<>();
        // 说明需要解密
        if (StrUtil.isNotEmpty(isEncrypted)) {
            // 需要对用户名和密码实行解密
            username = RsaUtil.decryptWithPrivateKey(username);
            if (StrUtil.isEmpty(username)) {
                return apiResult.failMsg("无效账号或密码！");
            }
            password = RsaUtil.decryptWithPrivateKey(password);
            if (StrUtil.isEmpty(password)) {
                return apiResult.failMsg("无效账号或密码！");
            }
            // 校验密码中不含有特殊字符
            if (StrUtil.containsAny(password, "+", "&", "%", "=", "*", "_")) {
                return apiResult.failMsg("请确保密码不含有 +&%=*_这5个特殊字符后进行登录！");
            }
        }
        // 校验账户是否存在
        SysUserEntity sysUser = sysUserDao.queryByUserName(username);
        if (sysUser == null) {
            return apiResult.failMsg("账号或密码错误！");
        }
        // 根据系统设置的认证flag来决定是否认证
        String isAuthFlag = configService.getIsAuth();
        if (Constant.AUTH.equals(isAuthFlag)) {
            // 需要配合OA统一认证,改为Base64加密 by Yu
            password = Base64.encode(password);
            /*
            校验登陆用户是否为特殊人员(即不属于任何部门的用户)
                    如果是，采用用户名/密码认证
                    如果不是，则走OA身份认证
             */
            if (StrUtil.isEmpty(sysUser.getDeptId())) {
                if (!password.equals(sysUser.getPassWord())) {
                    return apiResult.failMsg("账号或密码错误！");
                }
            } else {
                if (!doResCenterAuthenticate(username, password)) {
                    return apiResult.failMsg("账号或密码错误！");
                }
            }
        }
        // 校验账户是否锁定
        if (sysUser.getStatus() == 0) {
            return apiResult.failMsg("账号已被锁定,请联系管理员");
        }
        //生成token
        Map<String, Object> token = tokenService.createToken(sysUser.getUserId());
        // 设置返回的基础信息
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", sysUser);

        // 获取用户的角色信息
        List<String> roleIdList = sysUserRoleDao.queryRoleIdList(sysUser.getUserId());
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            data.put("roleId", roleIdList.get(0));
        }
        // 获取登录用户的部门类别
        String deptId = sysUser.getDeptId();
        if (StrUtil.isNotEmpty(deptId)) {
            String type = sysDeptService.getDeptTypeById(deptId);
            // 处于模具维修组、模具技术室或者是具有生产组长-模具维修身份的用户
            if (StrUtil.equalsAny(type, "DT_MJWXZ", "DT_MJJSS") || "e0916c82e4df4fafbb565977f81cab2c".equals(roleIdList.get(0))) {
                // 压铸组长、浇筑组长(待定) 模具维修组(DT_MJWXZ)  模具技术室(DT_MJJSS)
                data.put("flag", 0);
                data.put("type", type);
            } else if (StrUtil.equalsAny(type, "DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC")) {
                // 生产组班长(DT_SCGLS)、设备维修组组长(DT_SBWXZ)、机电维修工(DT_SBWXZ)、车间机电设备工程师(DT_SBJSS)
                data.put("type", type);
                data.put("flag", 1);
            }
        }
        // 添加登录成功日志
        baseCommonService.addLog("用户登录", "用户名: " + username + ",登录成功[移动端]！", CommonConstant.LOG_TYPE_1, null, CommonConstant.OPERATE_CLIENT_APP, sysUser);
        return apiResult.success(data);
    }

    /**
     * 单点登录
     */
    @CrossOrigin(origins = "*", maxAge = 3600)
    @IgnoreAuth
    @ApiOperation(value = "长安令牌登录API")
    @ApiImplicitParam(name = "identityToken", value = "长安认证中心颁发的用户身份令牌", paramType = "query", dataType = "String", required = true)
    @GetMapping("/ssoLogin")
    public ApiResult<Map> singleSignOn(@RequestParam("identityToken") String identityToken) {
        ApiResult<Map> apiResult = new ApiResult<>();
        if (StrUtil.isEmpty(identityToken)) {
            return apiResult.failMsg("用户令牌必填！");
        }
        // 校验用户身份令牌是否有效
        if (!resCenterAuthenticator.checkIdentityToken(identityToken)) {
            return apiResult.failMsg("用户身份令牌已失效，请退出登录后重试！");
        }
        // 根据用户令牌获取长安用户信息
        UserInfo currentUser = resCenterAuthenticator.getUserByToken(identityToken);
        if (currentUser == null) {
            return apiResult.failMsg("无效IdentityToken，获取用户信息失败！");
        }
        // 校验账户是否存在
        String username = currentUser.getLoginID();
        SysUserEntity sysUser = sysUserDao.queryByUserName(username);
        if (sysUser == null) {
            return apiResult.failMsg("非当前系统用户，不允许登录该系统！");
        }
        // 校验账户是否锁定
        if (sysUser.getStatus() == 0) {
            return apiResult.failMsg("账号已被锁定,请联系管理员");
        }
        //生成token
        Map<String, Object> token = tokenService.createToken(sysUser.getUserId());
        // 设置返回的基础信息
        Map<String, Object> data = new HashMap<>();
        data.put("token", token);
        data.put("user", sysUser);

        // 获取用户的角色信息
        List<String> roleIdList = sysUserRoleDao.queryRoleIdList(sysUser.getUserId());
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            data.put("roleId", roleIdList.get(0));
        }
        // 获取登录用户的部门类别
        String deptId = sysUser.getDeptId();
        if (StrUtil.isNotEmpty(deptId)) {
            String type = sysDeptService.getDeptTypeById(deptId);
            // 处于模具维修组、模具技术室或者是具有生产组长-模具维修身份的用户
            if (StrUtil.equalsAny(type, "DT_MJWXZ", "DT_MJJSS") || "e0916c82e4df4fafbb565977f81cab2c".equals(roleIdList.get(0))) {
                // 压铸组长、浇筑组长(待定) 模具维修组(DT_MJWXZ)  模具技术室(DT_MJJSS)
                data.put("flag", 0);
                data.put("type", type);
            } else if (StrUtil.equalsAny(type, "DT_SBWXZ", "DT_SBJSS", "DT_SCGLS", "DT_ZZC")) {
                // 生产组班长(DT_SCGLS)、设备维修组组长(DT_SBWXZ)、机电维修工(DT_SBWXZ)、车间机电设备工程师(DT_SBJSS)
                data.put("type", type);
                data.put("flag", 1);
            }
        }
        // 添加登录成功日志
        baseCommonService.addLog("用户登录", "用户名: " + username + ",登录成功[移动端]！", CommonConstant.LOG_TYPE_1, null, CommonConstant.OPERATE_CLIENT_APP, sysUser);
        return apiResult.success(data);
    }

    /**
     * 调用远程认证中心执行认证
     *
     * @param username 用户名
     * @param password 密码
     * @return
     */
    private boolean doResCenterAuthenticate(String username, String password) {
        // 认证中心应用ID
        String appId = configService.getValue("APPID", "");
        // 认证资源中心服务接口地址 http://cmpuat.changan.com/rescenter/services/ResCenterApi2
        String rescenterServiceUrl = configService.getRemoteServiceHost() + "/rescenter/services/ResCenterApi2";
        // 获取本机域名
        String host = configService.getValue("HOST", "");
        if (StrUtil.isEmpty(appId) || StrUtil.isEmpty(rescenterServiceUrl) || StrUtil.isEmpty(host)) {
            throw new RRException("认证信息配置不全!");
        }
        // 测试是否通
        boolean connectResult = ResCenterClient.connect(appId, rescenterServiceUrl);
        if (!connectResult) {
            throw new RRException("认证中心通信失败,请稍后重试!");
        }
        try {
            // 执行认证
            ResultMessage rntmsg = ResCenterClient.getResCenterApi().userLogin(username, password, host);
            return rntmsg != null && rntmsg.isIsSuccess();
        } catch (RemoteException e) {
            log.error("执行统一认证登陆时发生异常", e);
        }
        return false;
    }

}
